package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.service.IProductDetailsService;
import com.spzx.product.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.service.IProductSkuService;
import com.spzx.product.service.ISkuStockService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author xiongkunYang
 * @since 2025/05/26 18:30
 */
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    private final IProductSkuService productSkuService;

    private final ISkuStockService skuStockService;
    private final IProductDetailsService productDetailsService;
    private final RedisTemplate<Object, Object> redisTemplate;

    @Override
    public List<Product> productList() {
        return this.baseMapper.selectProductList();
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public int saveProduct(Product product) {

        AtomicInteger i = new AtomicInteger();
        product.getProductSkuList().forEach(sku -> {
            sku.setProductId(product.getId());
            sku.setSkuCode(product.getId() + "_" + i.getAndIncrement());
            sku.setSkuName(product.getName() + " " + sku.getSkuSpec());
            sku.setStatus(0);
            this.productSkuService.save(sku);

            // 添加商品库存
            SkuStock skuStock = SkuStock.builder()
                    .skuId(sku.getId())
                    .totalNum(sku.getStockNum())
                    .lockNum(0)
                    .availableNum(sku.getStockNum())
                    .saleNum(0)
                    .build();
            this.skuStockService.save(skuStock);
        });

        ProductDetails productDetails = ProductDetails.builder()
                .productId(product.getId())
                .imageUrls(String.join(",", product.getDetailsImageUrlList()))
                .build();
        this.productDetailsService.save(productDetails);

        return this.baseMapper.insert(product);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public int updateStatus(Long id, Integer status) {
        //  更新商品状态
        Product product = new Product();
        product.setId(id);
        product.setStatus(status.byteValue());
        int i = this.baseMapper.updateById(product);

        // 更新商品SKU状态
        boolean update = this.productSkuService.update(new LambdaUpdateWrapper<ProductSku>()
                .eq(ProductSku::getProductId, id)
                .set(ProductSku::getStatus, status.byteValue()));

        //更新bitmap
        String key = "product:sku:data";
        //获取所有当前商品下的skuId列表
        List<Object> productSkuIdList = this.productSkuService.listObjs(
                new LambdaQueryWrapper<ProductSku>()
                        .eq(ProductSku::getProductId, product.getId())
                        .select(ProductSku::getId)
        );
        //判断是上架还是下架
        if(status == 1){
            for (Object skuId : productSkuIdList) {
                this.redisTemplate.opsForValue().setBit(key, (Long) skuId, true);
            }
        }else if(status == -1){
            for (Object skuId : productSkuIdList) {
                this.redisTemplate.opsForValue().setBit(key, (Long) skuId, false);
            }
        }
        return (i > 0 && update) ? 1 : 0;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public int removeProductByIds(List<Long> ids) {

        // 查询skuIds
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<ProductSku>()
                .in(ProductSku::getProductId, ids)
                .select(ProductSku::getId);
        List<ProductSku> productSkuList = this.productSkuService.list(queryWrapper);
        Optional.ofNullable(productSkuList)
                .filter(list -> !list.isEmpty())
                .ifPresent(list -> {
                    List<Long> skuIds = list.stream().map(ProductSku::getId).toList();
                    this.productSkuService.removeByIds(skuIds);
                    this.skuStockService.remove(new LambdaUpdateWrapper<SkuStock>().in(SkuStock::getSkuId, skuIds));
                });


        // 删除商品详情
        this.productDetailsService.remove(new LambdaQueryWrapper<ProductDetails>()
                .in(ProductDetails::getProductId, ids));

        // 删除商品
        return this.baseMapper.deleteBatchIds(ids);
    }

}
